<?php

namespace app\admin\logic;

use com\Time;
use think\facade\Db;

/**
 * Class PanelLogic
 * @package app\admin\logic
 * @author Mr.Liu Wuchen
 * @create 2021-08-18 11:04
 */
class PanelLogic
{

    /**
     * 本月新增统计
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-08-18 17:06
     */
    public function getMonthNewData(): array
    {
        // 当前月
        $nowMonth = $this->getTotalByTime('month');
        // 上月
        $lastMonth = $this->getTotalByTime('lastMonth');

        // 线索
        $leadsNumCompare                = $nowMonth['leads_num'] - $lastMonth['leads_num'];
        $return['leads_num_compare']    = abs($leadsNumCompare);
        $return['leads_num_type']       = $leadsNumCompare > 0 ? 1 : ($leadsNumCompare < 0 ? -1 : 0);

        // 客户
        $customerNumCompare             = $nowMonth['customer_num'] - $lastMonth['customer_num'];
        $return['customer_num_compare'] = abs($customerNumCompare);
        $return['customer_num_type']    = $customerNumCompare > 0 ? 1 : ($customerNumCompare < 0 ? -1 : 0);

        // 商机
        $businessNumCompare             = $nowMonth['business_num'] - $lastMonth['business_num'];
        $return['business_num_compare'] = abs($businessNumCompare);
        $return['business_num_type']    = $businessNumCompare > 0 ? 1 : ($businessNumCompare < 0 ? -1 : 0);

        // 试样
        $sampleNumCompare               = $nowMonth['sample_num'] - $lastMonth['sample_num'];
        $return['sample_num_compare']   = abs($sampleNumCompare);
        $return['sample_num_type']      = $sampleNumCompare > 0 ? 1 : ($sampleNumCompare < 0 ? -1 : 0);

        // 成交客户
        $dealNumCompare                      = $nowMonth['deal_customer_num'] - $lastMonth['deal_customer_num'];
        $return['deal_customer_num_compare'] = abs($dealNumCompare);
        $return['deal_customer_num_type']    = $dealNumCompare > 0 ? 1 : ($dealNumCompare < 0 ? -1 : 0);

        // 成交额
        $orderAmountCompare             = bcsub($nowMonth['order_amount'], $lastMonth['order_amount'], 2);
        $return['order_amount_compare'] = bcadd(abs($orderAmountCompare), '0', 2);
        $return['order_amount_type']    = $orderAmountCompare > 0 ? 1 : ($orderAmountCompare < 0 ? -1 : 0);

        // 总线索数
        $leadsTotal    = Db::name('crm_leads')->count();
        $customerTotal = Db::name('crm_customer')->count();
        $dealTotal     = Db::name('crm_customer')->where('status', '=', 2)->count();

        // 触达率
        $leadsTotal && $touchRate = bcdiv($customerTotal, $leadsTotal, 2);
        $return['touch_rate'] = isset($touchRate) ? intval($touchRate * 100) : 0;

        // 转化率
        $customerTotal && $transRate = bcdiv($dealTotal, $customerTotal, 2);
        $return['trans_rate'] = isset($transRate) ? intval($transRate * 100) : 0;

        return array_merge($nowMonth, $return);
    }

    /**
     * 跟进时间获取统计总数
     * @param  string $type 时间类型
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-08-18 16:29
     */
    public function getTotalByTime(string $type = 'month'): array
    {
        $monthTime = getTimeByType($type);
        $where     = [];
        array_push($where, ['create_time', 'between', $monthTime]);
        // 线索数量
        $return['leads_num']    = Db::name('crm_leads')->where($where)->count();
        // 客户数量
        $return['customer_num'] = Db::name('crm_customer')->where($where)->count();
        // 商机数量
        $return['business_num'] = Db::name('crm_business')->where($where)->count();
        // 试样申请数量
        $sampWhere = $where;
        array_push($sampWhere, ['is_audit', '=', 2]);
        $return['sample_num']   = Db::name('shop_sample_apply')->where($where)->count();

        // 成交客户数量
        $dealWhere = $where;
        array_push($dealWhere, ['status', '=', 2]);
        $return['deal_customer_num'] = Db::name('crm_customer')->where($dealWhere)->count();

        // 成交额
        $orderWhere = $where;
        array_push($orderWhere, ['status', '=', 2]);
        $payAmount              = Db::name('shop_order')->where($orderWhere)->sum('pay_amount');
        $return['order_amount'] = bcadd($payAmount, '0', 2);

        return $return;
    }

    /**
     * 全国各区域客户关系转换及订单总金额统计 Top 10
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-08-23 17:37
     */
    public function getAreaCustomerTop(): array
    {
        $request['limit'] = 10;
        $list         = $this->getAreaCustomer($request);
        $data         = [];
        $data['data'] = $list ?? [];
        return $data;
    }

    /**
     * 全国各区域客户关系转换及订单总金额统计
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-08-19 11:45
     */
    public function getAreaCustomer(array $request): array
    {
        try {
            $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 0;
            $provinceId = $request['province_id'] ?? 0;
            $month      = $request['month'] ?? '';
            $monthTime  = Time::monthToTime($month);
            $return     = [];
            $where      = [];
            array_push($where, ['create_time', 'between', $monthTime]);
            $provinceId && array_push($where, ['province_id', '=', $provinceId]);
            $order = 'leads_num DESC';
            $group = 'province_id';
            $field = ['province_id', 'count(*)' => 'leads_num', 'group_concat(touch_user_id)' => 'touch_user_id_str'];
            $list  = Db::name('crm_leads')->where($where)->field($field)->group($group)
                ->when($request['limit'], function($query) use ($request) {
                    $query->limit($request['limit']);
                })
                ->order($order)->select()->toArray();
            if ($list) {
                $dataAll = [
                    'province_name'     => '总计',
                    'leads_num'         => 0,
                    'communal_num'      => 0,
                    'customer_num'      => 0,
                    'customer_deal_num' => 0,
                    'staffing_num'      => 0,
                    'business_num'      => 0,
                    'order_amount'      => '0.00',
                    'sample_num'        => 0,
                    'touch_rate'        => '0%',
                    'trans_rate'        => '0%'
                ];
                $userIdAll     = [];
                $provinceIdArr = array_column($list, 'province_id');
                $regionList    = Db::name('shop_region')->where('id', 'in', $provinceIdArr)->column('name', 'id');

                // 公海数量
                $communalWhere = $where;
                array_push($communalWhere, ['touch_user_id', '=', 0]);
                $communalField = ['province_id', 'count(*)' => 'num'];
                $communal      = Db::name('crm_leads')->where($communalWhere)->field($communalField)
                    ->group('province_id')->select()->toArray();
                $communalList = array_column($communal, 'num', 'province_id');

                // 客户
                $customerWhere = $where;
                $customerField = ['customer_id', 'trans_user_id', 'status', 'province_id'];
                $customer      = Db::name('crm_customer')->where($customerWhere)->field($customerField)->select()->toArray();
                $customerProvince = [];
                if ($customer) {
                    foreach ($customer as $key => $val) {
                        $customerProvince[$val['province_id']][] = $val;
                    }
                }

                // 获取省的所有客户
                $provinceCustomerList  = [];
                $provinceCustomerWhere = [];
                $provinceId && array_push($provinceCustomerWhere, ['province_id', '=', $provinceId]);
                $provinceCustomerField = ['customer_id', 'province_id'];
                $provinceCustomer      = Db::name('crm_customer')->where($provinceCustomerWhere)
                    ->field($provinceCustomerField)->select()->toArray();
                if ($provinceCustomer) {
                    foreach ($provinceCustomer as $key => $val) {
                        $provinceCustomerList[$val['province_id']][] = $val['customer_id'];
                    }
                }

                foreach ($list as $key => $val) {
                    $listValue                  = [];
                    $listValue['province_name'] = $regionList[$val['province_id']] ?? '未知';
                    $listValue['leads_num']     = $val['leads_num'];
                    $touchUserIdArr = array_filter(explode(',', $val['touch_user_id_str']));

                    // 公海数量
                    $listValue['communal_num'] = $communalList[$val['province_id']] ?? 0;

                    // 客户
                    $where = [
                        ['create_time', 'between', $monthTime],
                        ['province_id', '=', $val['province_id']],
                    ];
                    $customerIdArr   = [];
                    $customerDealNum = 0; // 成交客户数量
                    $transUserIdArr  = []; // 转化人
                    $customerList    = $customerProvince[$val['province_id']] ?? [];
                    if ($customerList) {
                        foreach ($customerList as $k => $v) {
                            array_push($customerIdArr, $v['customer_id']);
                            // 转化人
                            $v['trans_user_id'] && array_push($transUserIdArr, $v['trans_user_id']);
                            // 成交客户
                            $v['status'] == 2 && $customerDealNum++;
                        }
                    }
                    // 客户数量
                    $listValue['customer_num']      = count($customerIdArr);
                    // 成交客户数量
                    $listValue['customer_deal_num'] = $customerDealNum;
                    // 人员编制
                    $staffingUserIdArr              = array_unique(array_merge($touchUserIdArr, $transUserIdArr));
                    $listValue['staffing_num']      = count($staffingUserIdArr);
                    // 需要计算总计编制人员数量
                    $userIdAll                      = array_merge($userIdAll, $staffingUserIdArr);

                    // 获取省的所有客户
                    $customerIdList = $provinceCustomerList[$val['province_id']] ?? [];

                    // 商机
                    $where = [
                        ['create_time', 'between', $monthTime],
                        ['customer_id', 'in', $customerIdList]
                    ];
                    $businessIdArr = Db::name('crm_business')->where($where)->column('business_id');
                    // 商机数量
                    $listValue['business_num'] = count($businessIdArr);

                    // 成交额
                    $where = [
                        ['create_time', 'between', $monthTime],
                        ['uid', 'in', $customerIdList],
                        ['status', '=', 2]
                    ];
                    $payAmount                 = Db::name('shop_order')->where($where)->sum('pay_amount');
                    $listValue['order_amount'] = bcadd($payAmount, '0', 2);

                    // 试样次数
                    $where = [
                        ['business_id', 'in', $businessIdArr],
                        ['type', '=', 1]
                    ];
                    $listValue['sample_num'] = Db::name('shop_sample_record')->where($where)->count();

                    // 触达率
                    $val['leads_num'] && $touchRate = bcdiv($listValue['customer_num'], $val['leads_num'], 2);
                    $listValue['touch_rate'] = (isset($touchRate) ? $touchRate * 100 : 0) . '%';

                    // 转化率
                    $listValue['customer_num'] && $transRate = bcdiv($listValue['customer_deal_num'], $listValue['customer_num'], 2);
                    $listValue['trans_rate'] = (isset($transRate) ? $transRate * 100 : 0) . '%';

                    $return[] = $listValue;

                    // 总计
                    if (!$request['limit']) {
                        $dataAll['leads_num']         += $listValue['leads_num'];
                        $dataAll['communal_num']      += $listValue['communal_num'];
                        $dataAll['customer_num']      += $listValue['customer_num'];
                        $dataAll['customer_deal_num'] += $listValue['customer_deal_num'];
                        $dataAll['business_num']      += $listValue['business_num'];
                        $dataAll['order_amount']       = bcadd($dataAll['order_amount'], $listValue['order_amount'], 2);
                        $dataAll['sample_num']        += $listValue['sample_num'];
                    }
                }

                // 总计
                if (!$request['limit']) {
                    // 编制人员
                    $dataAll['staffing_num'] = count(array_unique($userIdAll));
                    // 触达率
                    $dataAll['leads_num'] && $touchRate = bcdiv($dataAll['customer_num'], $dataAll['leads_num'], 2);
                    $dataAll['touch_rate'] = (isset($touchRate) ? $touchRate * 100 : 0) . '%';

                    // 转化率
                    $dataAll['customer_num'] && $transRate = bcdiv($dataAll['customer_deal_num'], $dataAll['customer_num'], 2);
                    $dataAll['trans_rate'] = (isset($transRate) ? $transRate * 100 : 0) . '%';

                    array_unshift($return, $dataAll);
                }
            }
        } catch (\Exception $e) {
            $return = [];
        }

        return $return ?? [];
    }

    /**
     * 商品试样申请统计 Top 5
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-08-19 17:49
     */
    public function getSampleApplyTop(array $request): array
    {
        $request['page']  = 1;
        $request['limit'] = 5;
        $data = $this->getSampleApply($request);
        if (isset($data['list']) && $data['list']) {
            $list = $data['list'];
        }
        $data         = [];
        $data['data'] = $list ?? [];
        return $data;
    }

    /**
     * 商品试样申请统计
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-08-19 17:36
     */
    public function getSampleApply(array $request): array
    {
        try {
            $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
            $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
            $goodsName = $request['goods_name'] ?? '';
            $month     = $request['month'] ?? '';
            $monthTime = Time::monthToTime($month);
            $return    = [];
            $where     = [
                ['create_time', 'between', $monthTime],
                ['is_audit', '=', 2]
            ];
            // 搜索商品
            if ($goodsName) {
                $goodsWhere = [
                    ['name', 'like', '%' . $goodsName . '%']
                ];
                $searchGoodsIdArr = Db::name('shop_goods')->where($goodsWhere)->column('id');
                $searchGoodsIdArr = $searchGoodsIdArr ?: ['-1'];
                array_push($where, ['goods_id', 'in', $searchGoodsIdArr]);
            }

            $field    = ['goods_id', 'count(*)' => 'apply_num', 'sum(quantity)' => 'apply_quantity'];
            $order    = 'apply_quantity DESC';
            $group    = 'goods_id';
            $querySql = Db::name('shop_sample_apply')->where($where)->field($field)
                ->group($group)->order($order);
            $dataCount = $querySql->count();
            if ($dataCount) {
                $list  = $querySql->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                    ->select()->toArray();
                // 获取商品信息
                $goodsIdArr = array_column($list, 'goods_id');
                $field      = ['g.id' => 'goods_id', 'g.name' => 'goods_name', 's.sample_unit'];
                $goodsList  = Db::name('shop_goods')->alias('g')
                    ->join('shop_goods_sku s', 's.goods_id = g.id', 'LEFT')
                    ->join('shop_goods_unit u', 's.unit_id = u.unit_id', 'LEFT')
                    ->where('g.id', 'in', $goodsIdArr)->field($field)->select()->toArray();
                $goodsList = array_column($goodsList, null, 'goods_id');

                // 总申请数量
                $applyWhere = [
                    ['create_time', '<', $monthTime[1]],
                    ['is_audit', '=', 2]
                ];
                isset($searchGoodsIdArr) && array_push($applyWhere, ['goods_id', 'in', $searchGoodsIdArr]);
                $applyField        = ['goods_id', 'sum(quantity)' => 'quantity'];
                $totalQuantityList = Db::name('shop_sample_apply')->where($applyWhere)
                    ->field($applyField)->group('goods_id')->select()->toArray();
                $totalQuantityList = array_column($totalQuantityList, 'quantity', 'goods_id');

                // 全部损耗、使用总量
                $recordWhere = [
                    ['create_time', '<', $monthTime[1]],
                    ['type', 'in', [1, 3]]
                ];
                isset($searchGoodsIdArr) && array_push($recordWhere, ['goods_id', 'in', $searchGoodsIdArr]);
                $recordField     = ['sum(sample_quantity)' => 'sample_quantity', 'goods_id'];
                $useQuantityList = Db::name('shop_sample_record')->where($recordWhere)
                    ->field($recordField)->group('goods_id')->select()->toArray();
                $useQuantityList = array_column($useQuantityList, 'sample_quantity', 'goods_id');

                // 当月试用、损耗数量
                $recordTypeWhere = [
                    ['create_time', 'between', $monthTime],
                    ['type', 'in', [1, 3]]
                ];
                isset($searchGoodsIdArr) && array_push($recordTypeWhere, ['goods_id', 'in', $searchGoodsIdArr]);
                $sampleRecordList = [];
                $recordTypeField  = ['goods_id', 'type', 'sample_quantity'];
                $sampleRecordRet  = Db::name('shop_sample_record')->where($recordTypeWhere)
                    ->field($recordTypeField)->select()->toArray();
                if ($sampleRecordRet) {
                    foreach ($sampleRecordRet as $key => $val) {
                        if (!isset($sampleRecordList[$val['goods_id']][$val['type']])) {
                            $sampleRecordList[$val['goods_id']][$val['type']] = $val['sample_quantity'];
                        } else {
                            $sampleRecordList[$val['goods_id']][$val['type']] += $val['sample_quantity'];
                        }
                    }
                }

                foreach ($list as $key => $val) {
                    $sampleUnitName = $goodsList[$val['goods_id']]['sample_unit'] ?? '';
                    $listValue      = [];
                    // 商品名称
                    $listValue['goods_id']    = $val['goods_id'];
                    $listValue['goods_name']  = $goodsList[$val['goods_id']]['goods_name'] ?? '';
                    // 申请次数
                    $listValue['apply_num']   = $val['apply_num'];
                    // 申请数量
                    $listValue['apply_quantity']       = $val['apply_quantity'] . $sampleUnitName;
                    $listValue['apply_quantity_value'] = $val['apply_quantity'];

                    // 当月试用、损耗数量
                    $sampleRecord               = $sampleRecordList[$val['goods_id']] ?? [];
                    // 试用数量
                    $listValue['use_quantity']  = bcadd(($sampleRecord[1] ?? '0.00000'), '0', 5) . $sampleUnitName;;
                    // 损耗数量
                    $listValue['loss_quantity'] = bcadd(($sampleRecord[3] ?? '0.00000'), '0', 5) . $sampleUnitName;;

                    // 申请总数量
                    $totalQuantity = $totalQuantityList[$val['goods_id']] ?? '0.00';
                    // 损耗、试样总数量
                    $useQuantity   = $useQuantityList[$val['goods_id']] ?? '0.00';
                    // 剩余数量
                    $listValue['remain_quantity'] = bcsub($totalQuantity, $useQuantity, 5) . $sampleUnitName;;

                    $return[] = $listValue;
                }
            }
        } catch (\Exception $e) {
            $return = [];
        }

        $data              = [];
        $data['list']      = $return ?? [];
        $data['dataCount'] = $dataCount ?? 0;
        return $data;
    }

    /**
     * 获取商品的试样使用记录
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-08-20 10:31
     */
    public function getGoodsSampleUse(array $request): array
    {
        try {
            $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
            $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
            $customerName     = $request['customer_name'] ?? '';
            $goodsId    = $request['goods_id'] ?? 0;
            $userName   = $request['user_name'] ?? '';
            $provinceId = $request['province_id'] ?? 0;
            $month      = $request['month'] ?? '';
            $monthTime  = Time::monthToTime($month);

            // 获取商品名称
            if ($goodsId) {
                $goodsName = Db::name('shop_goods')->where('id', '=', $goodsId)->value('name', '');
            }

            $return     = [];
            $where      = [
                ['s.type', '=', 1],
                ['s.goods_id', '=', $goodsId],
                ['c.province_id', '=', $provinceId],
                ['s.create_time', 'between', $monthTime],
            ];
            // 搜索客户
            $customerName && array_push($where, ['c.name', 'like', '%' . $customerName . '%']);
            // 搜索员工
            if ($userName) {
                $userWhere = [
                    ['realname', 'like', '%' . $userName . '%']
                ];
                $userIdArr = Db::name('admin_user')->where($userWhere)->column('id');
                $userIdArr = $userIdArr ?: 0;
                array_push($where, ['s.owner_user_id', 'in', $userIdArr]);
            }

            $querySql = Db::name('shop_sample_record')->alias('s')
                ->join('crm_customer c', 'c.customer_id = s.customer_id', 'LEFT')
                ->where($where);
            $dataCount = $querySql->count();
            if ($dataCount) {
                $field = ['s.id', 'c.province_id', 'c.name' => 'customer_name', 's.customer_id',
                    's.owner_user_id', 's.remark', 's.sample_quantity', 's.sample_unit_name'];
                $order = 'id DESC';
                $list  = $querySql->field($field)->order($order)
                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                    ->select()->toArray();

                // 获取地区
                $regionIdArr = array_unique(array_column($list, 'province_id'));
                $regionWhere = [
                    ['id', 'in', $regionIdArr]
                ];
                $regionList  = Db::name('shop_region')->where($regionWhere)->column('name', 'id');

                // 获取员工
                $userIdArr = array_unique(array_column($list, 'owner_user_id'));
                $userWhere = [
                    ['id', 'in', $userIdArr]
                ];
                $userList  = Db::name('admin_user')->where($userWhere)->column('realname', 'id');

                foreach ($list as $key => $val) {
                    $sampleUnitName             = $val['sample_unit_name'];
                    $listValue                  = [];
                    $listValue['province_name'] = $regionList[$val['province_id']] ?? '未知';
                    $listValue['customer_name'] = $val['customer_name'];
                    $listValue['user_name']     = $userList[$val['owner_user_id']] ?? '';
                    $listValue['remark']        = $val['remark'];
                    $listValue['use_quantity']  = $val['sample_quantity'] . $sampleUnitName;

                    $return[] = $listValue;
                }
            }

            // 总计
            if ($return) {
                $totalQuantity = $querySql->sum('sample_quantity');
                $totalReturn   = [];
                $totalReturn['province_name'] = '总计';
                $totalReturn['customer_name'] = '--';
                $totalReturn['user_name']     = '--';
                $totalReturn['remark']        = '--';
                $totalReturn['use_quantity']  = bcadd($totalQuantity, '0', 5) . ($smallUnitName ?? '');

                array_unshift($return, $totalReturn);
            }
        } catch (\Exception $e) {
            $return = [];
        }

        $data              = [];
        $data['goodsName'] = $goodsName ?? '';
        $data['list']      = $return ?? [];
        $data['dataCount'] = $dataCount ?? 0;
        return $data;
    }

    /**
     * 试样商品业务员持有统计
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-08-20 10:54
     */
    public function getGoodsSampleUserHold(array $request): array
    {
        try {
            $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
            $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
            $goodsId    = $request['goods_id'] ?? 0;
            $userName   = $request['user_name'] ?? '';
            $provinceId = $request['province_id'] ?? 0;

            // 获取商品名称
            if ($goodsId) {
                $goodsName = Db::name('shop_goods')->where('id', '=', $goodsId)->value('name', '');
            }

            $return     = [];
            $where      = [
                ['s.goods_id', '=', $goodsId],
            ];
            // 搜索员工
            if ($userName) {
                $userWhere = [
                    ['realname', 'like', '%' . $userName . '%']
                ];
                $userIdArr = Db::name('admin_user')->where($userWhere)->column('id');
                $userIdArr = $userIdArr ?: '0';
                array_push($where, ['s.owner_user_id', 'in', $userIdArr]);
            }
            // 搜索省份
            if ($provinceId) {
                // 跟进省份获取部门ID
                $structureIdArr = (new \app\admin\model\Structure())->getStructureOrUserByProvince([$provinceId], 'structure');
                array_push($where, ['u.structure_id', 'in', $structureIdArr]);
            }

            $order     = 's.id DESC';
            $group     = 's.owner_user_id';
            $fieldTop  = ['u.id' => 'user_id', 'u.structure_id' => 'structure_id', 'u.realname',
                's.owner_user_id', 'sum(s.quantity)' => 'quantity', 'group_concat(s.id)' => 'sample_id_str'];
            $querySql  = Db::name('shop_sample')->alias('s')
                ->join('admin_user u', 'u.id = s.owner_user_id', 'LEFT')
                ->where($where);
            $dataCount = $querySql->group($group)->count();
            if ($dataCount) {
                $list  = $querySql->field($fieldTop)->group($group)->order($order)
                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                    ->select()->toArray();

                // 获取员工省份
                $structureList = array_column($list, 'structure_id', 'user_id');
                if ($structureList) {
                    // 获取员工所在省份
                    foreach ($structureList as $key => $val) {
                        $strWhere = [
                            ['pid_level', 'like', '%-' . $val . '-%'],
                        ];
                        $structureIdArr = Db::name('admin_structure')->where($strWhere)->column('id');
                        array_push($structureIdArr, $val);
                        $structureIdArr = array_unique($structureIdArr);
                        $strWhere = [
                            ['structure_id', 'in', $structureIdArr]
                        ];
                        $provinceArr = Db::name('admin_structure_region')->where($strWhere)->column('province_name');
                        $structureNameList[$key] = implode('、', array_unique($provinceArr));
                    }
                }

                foreach ($list as $key => $val) {
                    // 获取试样商品记录
                    $sampleIdArr = array_unique(explode(',', $val['sample_id_str']));
                    $sampleWhere = [
                        ['sample_id', 'in', $sampleIdArr]
                    ];
                    $field      = ['type', 'sum(sample_quantity)' => 'sample_quantity', 'sample_unit_name'];
                    $recordList = Db::name('shop_sample_record')->where($sampleWhere)->field($field)->group('type')->select()->toArray();
                    if ($recordList) {
                        $recordList = array_column($recordList, null, 'type');
                    }

                    $sampleUnitName = $recordList[1]['sample_unit_name'] ?? ($recordList[2]['sample_unit_name'] ?? ($recordList[3]['sample_unit_name'] ?? ''));
                    $listValue      = [];
                    $listValue['province_name']     = $structureNameList[$val['owner_user_id']] ?? '未知';
                    $listValue['user_name']         = $val['realname'] ?: '';
                    $listValue['now_quantity']      = bcadd($val['quantity'], '0', 2) . $sampleUnitName;
                    $listValue['use_quantity']      = bcadd($recordList[1]['sample_quantity'] ?? '0', '0', 5) . $sampleUnitName;
                    $listValue['loss_quantity']     = bcadd($recordList[3]['sample_quantity'] ?? '0', '0', 5) . $sampleUnitName;
                    $listValue['transfer_quantity'] = bcadd($recordList[2]['sample_quantity'] ?? '0', '0', 5) . $sampleUnitName;

                    $return[] = $listValue;
                }
            }

            // 总计
            if ($return) {
                $list        = $querySql->field($fieldTop)->group($group)->order($order)->select()->toArray();
                $sampleIdStr = implode(',', array_column($list, 'sample_id_str'));
                $sampleIdArr = array_unique(explode(',', $sampleIdStr));
                $sampleWhere = [
                    ['goods_id', '=', $goodsId],
                    ['type', 'in', [1, 2, 3]],
                    ['sample_id', 'in', $sampleIdArr]
                ];
                $field      = ['type', 'sum(sample_quantity)' => 'sample_quantity'];
                $recordList = Db::name('shop_sample_record')->where($sampleWhere)->field($field)->group('type')->select()->toArray();
                if ($recordList) {
                    $recordList = array_column($recordList, null, 'type');
                }

                $totalQuantity = $querySql->sum('quantity');
                $totalReturn   = [];
                $totalReturn['province_name']     = '总计';
                $totalReturn['user_name']         = '--';
                $totalReturn['now_quantity']      = bcadd($totalQuantity, '0', 2) . ($sampleUnitName ?? '');
                $totalReturn['use_quantity']      = bcadd($recordList[1]['sample_quantity'] ?? '0', '0', 5) . ($sampleUnitName ?? '');
                $totalReturn['loss_quantity']     = bcadd($recordList[3]['sample_quantity'] ?? '0', '0', 5) . ($sampleUnitName ?? '');
                $totalReturn['transfer_quantity'] = bcadd($recordList[2]['sample_quantity'] ?? '0', '0', 5) . ($sampleUnitName ?? '');

                array_unshift($return, $totalReturn);
            }
        } catch (\Exception $e) {
            $return = [];
        }

        $data              = [];
        $data['goodsName'] = $goodsName ?? '';
        $data['list']      = $return ?? [];
        $data['dataCount'] = $dataCount ?? 0;
        return $data;
    }

    /**
     * 大区商机处理统计 Top 5
     * @param  array $request
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-08-20 16:08
     */
    public function getAreaBusinessTop(array $request): array
    {
        try {
            $return    = [];
            $monthTime = getTimeByType('month');
            $where = [
                ['b.create_time', 'between', $monthTime]
            ];
            $order = 'business_num DESC';
            $group = 'c.province_id';
            $field = ['c.province_id', 'count(*)' => 'business_num'];
            $list  = Db::name('crm_business')->alias('b')
                ->join('crm_customer c', 'c.customer_id = b.customer_id', 'LEFT')
                ->where($where)->field($field)->group($group)->order($order)->limit(5)->select()->toArray();
            if ($list) {
                // 审核阶段的商机
                array_push($where, ['status_id', '=', 7]);
                $group = 'c.province_id';
                $field = ['c.province_id', 'count(*)' => 'business_num'];
                $audit = Db::name('crm_business')->alias('b')
                    ->join('crm_customer c', 'c.customer_id = b.customer_id', 'LEFT')
                    ->where($where)->field($field)->group($group)->select()->toArray();
                $audit && $audit = array_column($audit, 'business_num', 'province_id');

                // 地区
                $provinceIdArr = array_column($list, 'province_id');
                $regionList    = Db::name('shop_region')->where('id', 'in', $provinceIdArr)->column('name', 'id');
                foreach ($list as $key => $val) {
                    $listValue                  = [];
                    $listValue['province_name'] = $regionList[$val['province_id']] ?? '未知';
                    $listValue['business_num']  = $val['business_num'];
                    $listValue['audit_num']     = $audit[$val['province_id']] ?? 0;

                    $return[] = $listValue;
                }
            }
        } catch (\Exception $e) {
            $return = [];
        }

        $data         = [];
        $data['data'] = $return ?? [];
        return $data;
    }

    /**
     * 大区商机处理统计
     * @param  array $request
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-08-20 17:01
     */
    public function getAreaBusiness(array $request): array
    {
        try {
            $return     = [];
            $provinceId = $request['province_id'] ?? 0;
            $month      = $request['month'] ?? '';
            $monthTime  = Time::monthToTime($month);
            $where      = [
                ['b.create_time', 'between', $monthTime]
            ];
            $provinceId && array_push($where, ['c.province_id', '=', $provinceId]);
            $order = 'business_num DESC';
            $group = 'c.province_id';
            $field = ['c.province_id', 'count(*)' => 'business_num', 'group_concat(b.business_id)' => 'business_id_str'];
            $list  = Db::name('crm_business')->alias('b')
                ->join('crm_customer c', 'c.customer_id = b.customer_id', 'LEFT')
                ->where($where)->field($field)->group($group)->order($order)->select()->toArray();
            if ($list) {
                // 审核阶段的商机
                $dataAll = [
                    'province_id'   => 0,
                    'province_name' => '总计',
                    'trans_num'     => 0,
                    'business_num'  => 0,
                    'status_0'      => 0,
                    'status_4'      => 0,
                    'status_5'      => 0,
                    'status_6'      => 0,
                    'audit_1'       => 0,
                    'audit_2'       => 0,
                    'deal_rate'     => '0%',
                    'sample_num'    => 0
                ];
                $transList  = [];
                $statusList = [];
                $auditList  = [];
                $userIdAll  = [];
                $field      = ['c.province_id', 'b.status_id', 'b.is_audit', 'b.trans_user_id', 'b.business_id'];
                $business   = Db::name('crm_business')->alias('b')
                    ->join('crm_customer c', 'c.customer_id = b.customer_id', 'LEFT')
                    ->where($where)->field($field)->select()->toArray();
                if ($business) {
                    foreach ($business as $key => $val) {
                         // 业务员
                        if(!isset($transList[$val['province_id']])) {
                            $transList[$val['province_id']][] = $val['trans_user_id'];
                        } else {
                            array_push($transList[$val['province_id']], $val['trans_user_id']);
                        }
                        if ($val['status_id'] == 7) {
                            // 审核成功失败数量
                            if(!isset($auditList[$val['province_id']][$val['is_audit']])) {
                                $auditList[$val['province_id']][$val['is_audit']] = 1;
                            } else {
                                $auditList[$val['province_id']][$val['is_audit']]++;
                            }
                        } else {
                            // 跟进阶段数量
                            if(!isset($statusList[$val['province_id']][$val['status_id']])) {
                                $statusList[$val['province_id']][$val['status_id']] = 1;
                            } else {
                                $statusList[$val['province_id']][$val['status_id']]++;
                            }
                        }
                    }
                }

                // 地区
                $provinceIdArr = array_column($list, 'province_id');
                $regionList    = Db::name('shop_region')->where('id', 'in', $provinceIdArr)->column('name', 'id');

                foreach ($list as $key => $val) {
                    $transIdArr = array_unique($transList[$val['province_id']] ?? []);
                    $listValue  = [];
                    $listValue['province_id']   = $val['province_id'];
                    $listValue['province_name'] = $regionList[$val['province_id']] ?? '未知';
                    $listValue['trans_num']     = count($transIdArr);
                    $listValue['business_num']  = $val['business_num'];
                    $listValue['status_0']      = $statusList[$val['province_id']][0] ?? 0;
                    $listValue['status_4']      = $statusList[$val['province_id']][4] ?? 0;
                    $listValue['status_5']      = $statusList[$val['province_id']][5] ?? 0;
                    $listValue['status_6']      = $statusList[$val['province_id']][6] ?? 0;
                    $listValue['audit_1']       = $auditList[$val['province_id']][1] ?? 0;
                    $listValue['audit_2']       = $auditList[$val['province_id']][2] ?? 0;

                    // 成交率
                    $listValue['business_num'] && $dealRate = bcdiv($listValue['audit_1'], $listValue['business_num'], 2);
                    $listValue['deal_rate'] = (isset($dealRate) ? $dealRate * 100 : 0) . '%';

                    // 业务员
                    $userIdAll   = array_merge($userIdAll, $transIdArr);

                    // 试样次数
                    $sampleWhere = [
                        ['type', '=', 1],
                        ['business_id', 'in', $val['business_id_str']]
                    ];

                    $listValue['sample_num'] = Db::name('shop_sample_record')->where($sampleWhere)->count();

                    $return[] = $listValue;

                    // 总计
                    $dataAll['business_num'] += $listValue['business_num'];
                    $dataAll['status_0']     += $listValue['status_0'];
                    $dataAll['status_4']     += $listValue['status_4'];
                    $dataAll['status_5']     += $listValue['status_5'];
                    $dataAll['status_6']     += $listValue['status_6'];
                    $dataAll['audit_1']      += $listValue['audit_1'];
                    $dataAll['audit_2']      += $listValue['audit_2'];
                }

                // 业务员数量
                $dataAll['trans_num'] = count($userIdAll);

                // 转化率
                $dataAll['business_num'] && $dealRate = bcdiv($dataAll['audit_1'], $dataAll['business_num'], 2);
                $dataAll['deal_rate'] = (isset($dealRate) ? $dealRate * 100 : 0) . '%';

                array_unshift($return, $dataAll);
            }
        } catch (\Exception $e) {
            $return = [];
        }

        $data         = [];
        $data['data'] = $return ?? [];
        return $data;
    }

    /**
     * 区域商机业务员统计
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-08-25 11:03
     */
    public function getAreaBusinessTrans(array $request): array
    {
        try {
            $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
            $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
            $return     = [];
            $provinceId = $request['province_id'] ?? 0;
            $month      = $request['month'] ?? '';
            $monthTime  = Time::monthToTime($month);
            $whereTop   = [
                ['b.create_time', 'between', $monthTime],
                ['c.province_id', '=', $provinceId]
            ];
            if (!$provinceId) {
                return [];
            }
            $order = 'business_num DESC';
            $group = 'b.trans_user_id';
            $field = ['c.province_id', 'count(*)' => 'business_num', 'b.trans_user_id',
                                       'group_concat(b.business_id)' => 'business_id_str'];

            $querySql  = Db::name('crm_business')->alias('b')
                ->join('crm_customer c', 'c.customer_id = b.customer_id', 'LEFT')
                ->where($whereTop)->group($group);

            $dataCount = $querySql->count();
            if ($dataCount) {
                $list = $querySql->field($field)->order($order)
                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                    ->select()->toArray();
                $statusList = [];
                $auditList  = [];
                $field      = ['b.status_id', 'b.is_audit', 'b.trans_user_id', 'b.business_id'];
                $business   = Db::name('crm_business')->alias('b')
                    ->join('crm_customer c', 'c.customer_id = b.customer_id', 'LEFT')
                    ->where($whereTop)->field($field)->select()->toArray();
                if ($business) {
                    foreach ($business as $key => $val) {
                        if ($val['status_id'] == 7) {
                            // 审核成功失败数量
                            if(!isset($auditList[$val['trans_user_id']][$val['is_audit']])) {
                                $auditList[$val['trans_user_id']][$val['is_audit']] = 1;
                            } else {
                                $auditList[$val['trans_user_id']][$val['is_audit']]++;
                            }
                        } else {
                            // 跟进阶段数量
                            if(!isset($statusList[$val['trans_user_id']][$val['status_id']])) {
                                $statusList[$val['trans_user_id']][$val['status_id']] = 1;
                            } else {
                                $statusList[$val['trans_user_id']][$val['status_id']]++;
                            }
                        }
                    }
                }

                // 地区
                $provinceIdArr = array_column($list, 'province_id');
                $regionList    = Db::name('shop_region')->where('id', 'in', $provinceIdArr)->column('name', 'id');

                // 业务员
                $userIdArr = array_unique(array_column($list, 'trans_user_id'));
                $userList  = Db::name('admin_user')->where('id', 'in', $userIdArr)->column('realname', 'id');

                foreach ($list as $key => $val) {
                    $listValue  = [];
                    $listValue['province_name']   = $regionList[$val['province_id']] ?? '未知';
                    $listValue['trans_user_name'] = $userList[$val['trans_user_id']] ?? '';
                    $listValue['business_num']    = $val['business_num'];
                    $listValue['status_0']        = $statusList[$val['trans_user_id']][0] ?? 0;
                    $listValue['status_4']        = $statusList[$val['trans_user_id']][4] ?? 0;
                    $listValue['status_5']        = $statusList[$val['trans_user_id']][5] ?? 0;
                    $listValue['status_6']        = $statusList[$val['trans_user_id']][6] ?? 0;
                    $listValue['audit_1']         = $auditList[$val['trans_user_id']][1] ?? 0;
                    $listValue['audit_2']         = $auditList[$val['trans_user_id']][2] ?? 0;

                    // 成交率
                    $listValue['business_num'] && $dealRate = bcdiv($listValue['audit_1'], $listValue['business_num'], 2);
                    $listValue['deal_rate'] = (isset($dealRate) ? $dealRate * 100 : 0) . '%';

                    // 试样次数
                    $sampleWhere = [
                        ['type', '=', 1],
                        ['business_id', 'in', $val['business_id_str']]
                    ];

                    $listValue['sample_num'] = Db::name('shop_sample_record')->where($sampleWhere)->count();

                    $return[] = $listValue;
                }

                // 总计
                if ($return) {
                    $statusList   = [];
                    $auditList    = [];
                    $businessNum  = 0;
                    $field        = ['b.status_id', 'b.is_audit', 'b.business_id'];
                    $businessList = Db::name('crm_business')->alias('b')
                        ->join('crm_customer c', 'c.customer_id = b.customer_id', 'LEFT')
                        ->where($whereTop)->field($field)->select()->toArray();
                    if ($businessList) {
                        foreach ($businessList as $key => $val) {
                            if ($val['status_id'] == 7) {
                                // 审核成功失败数量
                                if(!isset($auditList[$val['is_audit']])) {
                                    $auditList[$val['is_audit']] = 1;
                                } else {
                                    $auditList[$val['is_audit']]++;
                                }
                            } else {
                                // 跟进阶段数量
                                if(!isset($statusList[$val['status_id']])) {
                                    $statusList[$val['status_id']] = 1;
                                } else {
                                    $statusList[$val['status_id']]++;
                                }
                            }
                            $businessNum++;
                        }

                        // 试样次数
                        $sampleWhere = [
                            ['type', '=', 1],
                            ['business_id', 'in', array_column($businessList, 'business_id')]
                        ];

                        $sampleNum = Db::name('shop_sample_record')->where($sampleWhere)->count();

                        // 转化率
                        $businessNum && $dealRate = bcdiv($auditList[1] ?? 0, $businessNum, 2);
                        $dealRate = (isset($dealRate) ? $dealRate * 100 : 0) . '%';

                        $dataAll = [
                            'province_name'   => '总计',
                            'trans_user_name' => '--',
                            'business_num'    => $businessNum,
                            'status_0'        => $statusList[0] ?? 0,
                            'status_4'        => $statusList[4] ?? 0,
                            'status_5'        => $statusList[5] ?? 0,
                            'status_6'        => $statusList[6] ?? 0,
                            'audit_1'         => $auditList[1] ?? 0,
                            'audit_2'         => $auditList[2] ?? 0,
                            'deal_rate'       => $dealRate,
                            'sample_num'      => $sampleNum
                        ];

                        array_unshift($return, $dataAll);
                    }
                }


            }
        } catch (\Exception $e) {
            $return = [];
        }

        $data              = [];
        $data['list']      = $return ?? [];
        $data['dataCount'] = $dataCount ?? 0;
        return $data;
    }

    /**
     * 待处理事项
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-08-23 13:44
     */
    public function getWaitHandle(array $request): array
    {
        try {
            $return = [];
            // 待进入公海线索
            $where  = $this->getMergeParamsByMenuType(1);
            $return['communal_prep_num'] = Db::name('crm_leads')->where($where)->count();
            // 公海
            $where  = $this->getMergeParamsByMenuType(2);
            $return['communal_num'] = Db::name('crm_leads')->where($where)->count();
            // 处理中的商机
            $where  = $this->getMergeParamsByMenuType(3);
            $return['business_ing_num'] = Db::name('crm_business')->where($where)->count();
            // 超时未跟进的商机
            $where  = $this->getMergeParamsByMenuType(4);
            $return['business_over_time_num'] = Db::name('crm_business')->where($where)->count();
            // 未回款的订单
            $where  = $this->getMergeParamsByMenuType(5);
            $return['order_no_payment_num'] = Db::name('shop_order')->where($where)->count();
            // 审批中的试样申请
            $where  = $this->getMergeParamsByMenuType(6);
            $return['sample_audit_num'] = Db::name('shop_sample_apply')->where($where)->count();

        } catch (\Exception $e) {
            $return = [];
        }

        $data         = [];
        $data['data'] = $return ?? [];
        return $data;
    }

    /**
     * 跟进类型获取查询条件
     * @param $type
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-08-23 16:23
     */
    protected function getMergeParamsByMenuType($type): array
    {
        // 获取配置
        $config    = (new \app\admin\model\Setting())->getConfigByGroupName('admin_customer_set');
        $config    = array_column($config, 'value', 'name');
        $monthTime = getTimeByType('month');
        $where     = [];
        array_push($where, ['create_time', 'between', $monthTime]);
        switch ($type) {
            case 1:
                // 待进入公海的线索
                $leadsTime = $config['leads_time'] ?? 0;
                if (isset($config['switch']) && $config['switch']) {
                    array_push($where, ['touch_time', '<=',time() - $leadsTime * 86400]);
                    array_push($where, ['is_transform', 'in', [2,3]]);
                } else {
                    array_push($where, ['leads_id', '=', 0]);
                }
                break;
            case 2:
                // 公海
                array_push($where, ['touch_user_id', '=', 0]);
                break;
            case 3:
                // 处理中的商机
                array_push($where, ['status_id', 'in', [4, 5, 6]]);
                break;
            case 4:
                // 超时未跟进的商机
                $overtime = $config['business_time'] ?? -1;
                if ($overtime > 0) {
                    array_push($where, ['last_time', '>=', $overtime * 86400]);
                } else {
                    array_push($where, ['last_time', '=', -1]);
                }
                break;
            case 5:
                // 未回款的订单
                $config['return_money_status'] = $config['return_money_status'] ?? -1;
                if ($config['return_money_status'] == 4) {
                    $config['return_money_status'] = $config['return_money_time'] ?? -1;
                }
                $returnMoneyStatus = $config['return_money_status'] ?? -1;
                if (in_array($returnMoneyStatus, [1, 2, 3])) {
                    array_push($where, ['status', '>=', $returnMoneyStatus]);
                    array_push($where, ['status', '<', 5]);
                } else {
                    if ($returnMoneyStatus > 0) {
                        array_push($where, ['status', '=', 4]);
                        array_push($where, ['complete_time', '<=', time() - $returnMoneyStatus * 86400]);
                    } else {
                        array_push($where, ['status', '=', $returnMoneyStatus]);
                    }
                }
                break;
            case 6:
                // 审批中的试样申请
                array_push($where, ['is_audit', '=', 1]);
                break;
            default:
                break;
        }

        return $where;
    }

    /**
     * 本年月度报货订单趋势图
     * @return array
     * @author SL
     * @create 2021-08-18
     */
    public function getDataList($param)
    {
        $year = isset($param['year']) && $param['year'] ? $param['year'] : ''; // 年
        $province = isset($param['province']) && $param['province'] ? $param['province'] : ''; // 省份id
        $month = ['1','2','3','4','5','6','7','8','9','10','11','12'];
        $start_time = strtotime(date($year . '-1'));
        $end_time = strtotime(date($year . '-12-31 23:59:59'));

        $where = [];
        $where = [
            ['status', 'in', [2,3,4,5]],
            ['create_time', 'between', "$start_time,$end_time"]
        ];
        $res = [];
        $list = [];
        $res = Db::name('shop_order')->field('count(id) as order_num, sum(pay_amount) as pay_amount, group_concat(uid) as customer_num, month(from_unixtime(create_time)) as month')->where($where)->group('month')->select()->toArray();
        foreach ($res as $k => $v) 
        {
            $res[$k]['customer_num'] = count(array_unique(explode(',', $v['customer_num'])));
        }
        $res = array_column($res, null, 'month');
        foreach ($month as $key => $value) 
        {
            if(isset($res[$value]))
            {
                $list[] = $res[$value];
            }
            else{
                $list[] = [
                    'order_num'     =>0,
                    'pay_amount'    =>'0.00',
                    'customer_num'  =>0,
                    'month'         => $value
                ];
            }
        }
        return $list;
    }

    /**
     * 报货订单年度分月统计
     * @return Json
     * @author SL
     * @create 2021-08-18
     */
    /*public function getRegionDataList($param)
    {
        $year = isset($param['year']) && $param['year'] ? $param['year'] : ''; // 年
        $province = isset($param['province']) && $param['province'] ? $param['province'] : ''; // 省份id
        $month = ['1','2','3','4','5','6','7','8','9','10','11','12'];
        $start_time = strtotime(date($year . '-1'));
        $end_time = strtotime(date($year . '-12-31 23:59:59'));

        $where = [];
        $where = [
            // ['status', 'in', [2,3,4,5]],
            ['create_time', 'between', "$start_time,$end_time"]
        ];
        if($province)
        {
            array_push($where, ['province', '=', $province]);
        }

        $res = Db::name('shop_order')->field('sum(pay_amount) as pay_amount,month(from_unixtime(create_time)) as month,province')->where($where)->group('month,province')->select()->toArray();

        $total_amount = 0;
        $month_amount = []; // 各月所有省金额总计
        $area_amount = []; // 各省所有月金额总计
        foreach($res as $r => $v)
        {
            $total_amount += $v['pay_amount'];
            $list[$v['month'] . '_' . $v['province']] = $v;
            // 各月所有省金额总计
            if(isset($month_amount[$v['month']]))
            {
                $month_amount[$v['month']]['pay_amount'] += $v['pay_amount'];
            }
            else{
                $month_amount[$v['month']] = $v;
            }
            // 各省所有月金额总计
            if(isset($area_amount[$v['province']]))
            {
                $area_amount[$v['province']]['pay_amount'] += $v['pay_amount'];
            }
            else{
                $area_amount[$v['province']] = $v;
            }
        }
        
        $province = array_unique(array_column($res,'province'));
        foreach ($month as $key => $value) 
        {
            // 各月所有省金额总计
            if(isset($month_amount[$value]))
            {
                $month_pay_amount[$value] = $month_amount[$value]['pay_amount'] . '';
            }
            else{
                $month_pay_amount[$value] = '--';
            }

            foreach ($province as $k => $v) 
            {
                if(!isset($list[$value . '_' . $v]))
                {
                    $list[$value . '_' . $v] = [
                        'pay_amount' => '--',
                        'month' => $value,
                        'province' => $v
                    ];
                }
            }
        }
        // 省名称
        $where = [];
        $where = [
            ['level', '=', 1],
            ['id', 'in', $province]
        ];
        $region = Db::name('shop_region')->where($where)->column('name','id');
        foreach($province as $p => $pv)
        {
            // 各省所有月金额总计
            if(isset($area_amount[$pv]))
            {
                $area_pay_amount[$pv]['pay_amount'] = $area_amount[$pv]['pay_amount'] . '';
            }
            else{
                $area_pay_amount[$pv]['pay_amount'] = '--';
            }
            $area_pay_amount[$pv]['province_name'] = $region[$pv];
        }
        $data = [
            'total_amount' => $total_amount,
            'month_amount' => $month_pay_amount ?? [],
            'area_amount'  => $area_pay_amount ?? [],
            'list'         => $list ?? []
        ];
        return $data;
    }*/

    /**
     * 报货订单年度分月统计
     * @return Json
     * @author SL
     * @create 2021-08-18
     */
    public function getRegionDataList($param)
    {
        $year = isset($param['year']) && $param['year'] ? $param['year'] : ''; // 年
        $province = isset($param['province']) && $param['province'] ? $param['province'] : ''; // 省份id
        $month = ['1','2','3','4','5','6','7','8','9','10','11','12'];
        $start_time = strtotime(date($year . '-1'));
        $end_time = strtotime(date($year . '-12-31 23:59:59'));

        $where = [];
        $where = [
            ['status', 'in', [2,3,4,5]],
            ['create_time', 'between', "$start_time,$end_time"]
        ];
        if($province)
        {
            array_push($where, ['province', '=', $province]);
        }

        $res = Db::name('shop_order')->field('sum(pay_amount) as pay_amount,month(from_unixtime(create_time)) as month,province')->where($where)->group('month,province')->select()->toArray();
        if(!$res)
        {
            $data = [];
            $data['dataCount'] = 0;
            $data['list'] = [];
            return $data;
        }
        
        $total_amount = 0;
        $month_amount = []; // 各月所有省金额总计
        $area_amount = []; // 各省所有月金额总计
        $list = [];
        foreach($res as $r => $v)
        {
            $total_amount += $v['pay_amount'];
            $list[$v['province']][] = $v;
            // 各月所有省金额总计
            if(isset($month_amount[$v['month']]))
            {
                $month_amount[$v['month']]['pay_amount'] += $v['pay_amount'];
            }
            else{
                $month_amount[$v['month']] = $v;
            }
            // 各省所有月金额总计
            if(isset($area_amount[$v['province']]))
            {
                $area_amount[$v['province']]['pay_amount'] += $v['pay_amount'];
            }
            else{
                $area_amount[$v['province']] = $v;
            }
        }

        foreach ($month as $key => $value) 
        {
            // 各月所有省金额总计
            if(isset($month_amount[$value]))
            {
                $month_pay_amount['month_' . $value] = $month_amount[$value]['pay_amount'] . '';
            }
            else{
                $month_pay_amount['month_' . $value] = '--';
            }
        }
        $province = array_unique(array_column($res,'province'));
        // 省名称
        $where = [];
        $where = [
            ['level', '=', 1],
            ['id', 'in', $province]
        ];
        $region = Db::name('shop_region')->where($where)->column('name','id');
        foreach($list as $key => $value)
        {
            $valueArr = array_column($value, null, 'month');
            foreach($month as $k => $v)
            {
                $arr[$key]['province_id'] = $key;
                $arr[$key]['province_name'] = $region[$key];
                $arr[$key]['total_amount'] = $area_amount[$key]['pay_amount'] . '' ?? '--';
                if(isset($valueArr[$v]))
                {
                    $arr[$key]['month_' . $v] = $valueArr[$v]['pay_amount'] . '';
                }
                else{
                    $arr[$key]['month_' .$v] = '--';
                }
            }
        }
        // 总计
        $totalArr = [
            'province_id' => 0,
            'province_name' => '总计',
            'total_amount' => $total_amount .'',
        ];
        $totalArr = $totalArr + $month_pay_amount;
        array_unshift($arr, $totalArr);
        return $arr;
    }

    /**
     * 客户报货订单年度分月统计
     * @return Json
     * @author SL
     * @create 2021-08-18
     */
    public function getCustomerDataList($param)
    {
        $year = isset($param['year']) && $param['year'] ? $param['year'] : ''; // 年
        $province = isset($param['province']) && $param['province'] ? $param['province'] : ''; // 省份id
        $customer_name = isset($param['customer_name']) && $param['customer_name'] ? $param['customer_name'] : ''; // 客户名称
        $month = ['1','2','3','4','5','6','7','8','9','10','11','12'];
        $start_time = strtotime(date($year . '-1'));
        $end_time = strtotime(date($year . '-12-31 23:59:59'));

        $where = [];
        $where = [
            ['o.status', 'in', [2,3,4,5]],
            ['o.create_time', 'between', "$start_time,$end_time"]
        ];
        if($province)
        {
            array_push($where, ['o.province', '=', $province]);
        }
        if($customer_name)
        {
            array_push($where, ['c.name', 'like', "%$customer_name%"]);
        }

        // 按月分组,计算每个月所有客户的总计
        $month_amount = Db::name('shop_order')->alias('o')
            ->join('crm_customer c', 'o.uid = c.customer_id')
            ->field('sum(o.pay_amount) as pay_amount,month(from_unixtime(o.create_time)) as month')
            ->where($where)
            ->group('month')
            ->select()->toArray();
        if(!$month_amount)
        {
            $data = [];
            $data['dataCount'] = 0;
            $data['list'] = [];
            return $data;
        }
        $total_amount = array_sum(array_column($month_amount,'pay_amount'));
        $month_amount = array_column($month_amount,null,'month');
        foreach ($month as $key => $value) 
        {
            // 各月所有客户金额总计
            if(isset($month_amount[$value]))
            {
                $month_pay_amount['month_' . $value] = $month_amount[$value]['pay_amount'] . '';
            }
            else{
                $month_pay_amount['month_' . $value] = '--';
            }
        }
        // 总条数
        $dataCount = Db::name('shop_order')->alias('o')
            ->join('crm_customer c', 'o.uid = c.customer_id')
            ->field('o.uid')
            ->where($where)
            ->group('o.uid')
            ->count();
        // 按客户分组,计算每个客户所有月的总计
        $res_uid = Db::name('shop_order')->alias('o')
            ->join('crm_customer c', 'o.uid = c.customer_id')
            ->field('sum(o.pay_amount) as total_amount,o.uid,c.name,group_concat(o.id) as order_id,from_unixtime(max(o.create_time)) as last_create_time')
            ->where($where)
            ->group('o.uid')
            ->order('total_amount desc')
            ->limit(($param['page'] - 1) * $param['limit'], $param['limit'])->select()->toArray();

        // 获取当前页客户订单数据
        // $uidArr = array_column($res_uid,'uid');
        $order_id = explode(',', implode(',',array_column($res_uid,'order_id')));
        $arr = array_column($res_uid,null,'uid');

        $owhere = [];
        $owhere = [
            ['id', 'in', $order_id]
        ];
        $all_order = Db::name('shop_order')
            ->field('pay_amount,uid,month(from_unixtime(create_time)) as month,create_time')
            ->where($owhere)
            ->select()->toArray();
        foreach($all_order as $key => $value)
        {
            $list[$value['uid']][] = $value;
        }

        foreach($list as $key => $value)
        {
            foreach($value as $kv => $va)
            {
                if(isset($valueArr[$va['month']]))
                {
                    $valueArr[$va['month']] = $valueArr[$va['month']] +  $va['pay_amount'];
                }
                else{
                    $valueArr[$va['month']] = $va['pay_amount'];
                }
            }

            foreach($month as $k => $v)
            {
                if(isset($valueArr[$v]))
                {
                    $arr[$key]['month_' . $v] = $valueArr[$v] . '';
                }
                else{
                    $arr[$key]['month_' . $v] = '--';
                }
            }

            unset($valueArr);
        }
        
        // 总计
        $totalArr = [
            'uid' => 0,
            'name' => '总计',
            'total_amount' => $total_amount .'',
            'order_id' => '',
            'last_create_time' => ''
        ];
        $totalArr = $totalArr + $month_pay_amount;

        $data = [];
        $data['dataCount'] = $dataCount ?? 0;

        array_unshift($arr, $totalArr);

        $data['list'] = $arr ?? [];
        return $data;
    }

    /**
     * 业务员报货订单年度分月统计
     * @return Json
     * @author SL
     * @create 2021-08-18
     */
    public function getSalesDataList($param)
    {
        $year = isset($param['year']) && $param['year'] ? $param['year'] : ''; // 年
        $province = isset($param['province']) && $param['province'] ? $param['province'] : ''; // 省份id
        $month = ['1','2','3','4','5','6','7','8','9','10','11','12'];
        $start_time = strtotime(date($year . '-1'));
        $end_time = strtotime(date($year . '-12-31 23:59:59'));

        $where = [];
        $where = [
            ['o.status', 'in', [2,3,4,5]],
            ['o.create_time', 'between', "$start_time,$end_time"]
        ];
        if ($province) 
        {
            // 根据省份获取部门ID
            $structureIdArr = (new \app\admin\model\Structure())->getStructureOrUserByProvince([$province], 'structure');
            array_push($where, ['u.structure_id', 'in', $structureIdArr]);
        }

        // 按月分组,计算每个月所有业务员的总计
        $month_amount = Db::name('shop_order')->alias('o')
            ->join('admin_user u', 'o.customer_trans_id = u.id')
            ->field('sum(o.pay_amount) as pay_amount,month(from_unixtime(o.create_time)) as month')
            ->where($where)
            ->group('month')
            ->select()->toArray();
        if(!$month_amount)
        {
            $data = [];
            $data['dataCount'] = 0;
            $data['list'] = [];
            return $data;
        }
        $total_amount = array_sum(array_column($month_amount,'pay_amount'));
        $month_amount = array_column($month_amount,null,'month');
        foreach ($month as $key => $value) 
        {
            // 各月所有业务员金额总计
            if(isset($month_amount[$value]))
            {
                $month_pay_amount['month_' . $value] = $month_amount[$value]['pay_amount'] . '';
            }
            else{
                $month_pay_amount['month_' . $value] = '--';
            }
        }

        // 总条数
        $dataCount = Db::name('shop_order')->alias('o')
            ->join('admin_user u', 'o.customer_trans_id = u.id')
            ->field('o.customer_trans_id')
            ->where($where)
            ->group('o.customer_trans_id')
            ->count();
        // 按客户分组,计算每个客户所有月的总计
        $res_customerid = Db::name('shop_order')->alias('o')
            ->join('admin_user u', 'o.customer_trans_id = u.id')
            ->field('sum(o.pay_amount) as total_amount,o.customer_trans_id,u.structure_id,u.username,u.realname,group_concat(o.id) as order_id')
            ->where($where)
            ->group('o.customer_trans_id')
            ->order('total_amount desc')
            ->limit(($param['page'] - 1) * $param['limit'], $param['limit'])->select()->toArray();

        // 获取员工省份
        $structureList = array_column($res_customerid, 'structure_id', 'customer_trans_id');
        if ($structureList) {
            // 获取员工所在省份
            foreach ($structureList as $key => $val) {
                $strWhere = [
                    ['pid_level', 'like', '%-' . $val . '-%'],
                ];
                $structureIdArr = Db::name('admin_structure')->where($strWhere)->column('id');
                array_push($structureIdArr, $val);
                $structureIdArr = array_unique($structureIdArr);
                $strWhere = [
                    ['structure_id', 'in', $structureIdArr]
                ];
                $provinceArr = Db::name('admin_structure_region')->where($strWhere)->column('province_name');
                $structureNameList[$key] = implode('、', array_unique($provinceArr));
            }
        }
        foreach($res_customerid as $k => $v)
        {
            $res_customerid[$k]['province_name'] = $structureNameList[$v['customer_trans_id']];
        }
        // 获取当前页业务员订单数据
        $order_id = explode(',', implode(',',array_column($res_customerid,'order_id')));
        $arr = array_column($res_customerid,null,'customer_trans_id');

        $owhere = [];
        $owhere = [
            ['id', 'in', $order_id]
        ];
        $all_order = Db::name('shop_order')
            ->field('pay_amount,customer_trans_id,month(from_unixtime(create_time)) as month,create_time')
            ->where($owhere)
            ->select()->toArray();
        foreach($all_order as $key => $value)
        {
            $list[$value['customer_trans_id']][] = $value;
        }

        foreach($list as $key => $value)
        {
            foreach($value as $kv => $va)
            {
                if(isset($valueArr[$va['month']]))
                {
                    $valueArr[$va['month']] = $valueArr[$va['month']] +  $va['pay_amount'];
                }
                else{
                    $valueArr[$va['month']] = $va['pay_amount'];
                }
            }
        
            foreach($month as $k => $v)
            {
                if(isset($valueArr[$v]))
                {
                    $arr[$key]['month_' . $v] = $valueArr[$v] . '';
                }
                else{
                    $arr[$key]['month_' . $v] = '--';
                }
            }

            unset($valueArr);
        }
        
        // 总计
        $totalArr = [
            'total_amount' => $total_amount .'',
            'customer_trans_id' => 0,
            'structure_id' => 0,
            'username' => '总计',
            'realname' => '总计',
            'order_id' => '',
            'province_name' => ''
        ];
        $totalArr = $totalArr + $month_pay_amount;

        $data = [];
        $data['dataCount'] = $dataCount ?? 0;

        array_unshift($arr, $totalArr);

        $data['list'] = $arr ?? [];
        return $data;
    }

    /**
     * 客户报货金额统计(TOP5)
     * @return array
     * @author SL
     * @create 2021-08-18
     */
    public function getCustomerTopDataList($param)
    {
        $start_time = strtotime(date('Y-m'));
        $end_time = time();
        $where = [];
        $where = [
            ['o.status', 'in', [2,3,4,5]],
            ['o.create_time', 'between', "$start_time,$end_time"]
        ];
        $list = Db::name('shop_order')->alias('o')
            ->join('crm_customer c', 'o.uid = c.customer_id')
            ->join('shop_region r', 'c.province_id = r.id')
            ->field('sum(o.pay_amount) as total_amount,o.uid,c.name as customer_name,r.name as province_name,from_unixtime(max(o.create_time)) as last_create_time')
            ->where($where)
            ->group('o.uid')
            ->order('total_amount desc')
            ->limit(0, 5)
            ->select()->toArray();
        $list = $list ?? [];
        return $list;
    }

    /**
     * 标品销售金额统计(TOP5)
     * @return Json
     * @author SL
     * @create 2021-08-18
     */
    public function getGoodsTopDataList($param)
    {
        $start_time = strtotime(date('Y-m'));
        $end_time = time();
        $where = [];
        $where = [
            ['o.status', 'in', [2,3,4,5]],
            ['o.create_time', 'between', "$start_time,$end_time"],
            ['g.is_standard_product', '=', 1]
        ];
        $list = Db::name('shop_order_goods')->alias('og')
            ->join('shop_order o', 'og.order_id = o.id')
            ->join('shop_goods g', 'og.goods_id = g.id')
            ->field('sum(og.pay_price * og.number) as total_amount,g.name as goods_name')
            ->where($where)
            ->group('og.goods_id')
            ->order('total_amount desc')
            ->limit(0, 5)
            ->select()->toArray();
        $list = $list ?? [];
        return $list;
    }

    /**
     * 商品报货订单年度分月统计
     * @return Json
     * @author SL
     * @create 2021-08-18
     */
    public function getGoodsDataList($param)
    {
        $year = isset($param['year']) && $param['year'] ? $param['year'] : ''; // 年
        $province = isset($param['province']) && $param['province'] ? $param['province'] : ''; // 省份id
        $month = ['1','2','3','4','5','6','7','8','9','10','11','12'];
        $start_time = strtotime(date($year . '-1'));
        $end_time = strtotime(date($year . '-12-31 23:59:59'));

        $where = [];
        $where = [
            ['o.status', 'in', [2,3,4,5]],
            ['o.create_time', 'between', "$start_time,$end_time"],
            ['g.is_standard_product', '=', 1]
        ];
        if($province)
        {
            array_push($where, ['o.province', '=', $province]);
        }

        // 按月分组,计算每个月所有商品的总计
        $month_amount = Db::name('shop_order_goods')->alias('og')
            ->join('shop_order o', 'og.order_id = o.id')
            ->join('shop_goods g', 'og.goods_id = g.id')
            ->field('sum(og.pay_price * og.number) as pay_amount,month(from_unixtime(o.create_time)) as month')
            ->where($where)
            ->group('month')
            ->select()->toArray();
        if(!$month_amount)
        {
            $data = [];
            $data['dataCount'] = 0;
            $data['list'] = [];
            return $data;
        }
        $total_amount = array_sum(array_column($month_amount,'pay_amount'));
        $month_amount = array_column($month_amount,null,'month');
        foreach ($month as $key => $value) 
        {
            // 各月所有商品金额总计
            if(isset($month_amount[$value]))
            {
                $month_pay_amount['month_' . $value] = $month_amount[$value]['pay_amount'] . '';
            }
            else{
                $month_pay_amount['month_' . $value] = '--';
            }
        }

        // 总条数
        $dataCount = Db::name('shop_order_goods')->alias('og')
            ->join('shop_order o', 'og.order_id = o.id')
            ->join('shop_goods g', 'og.goods_id = g.id')
            ->field('og.goods_id')
            ->where($where)
            ->group('og.goods_id')
            ->count();
        // 按商品分组,计算每个商品所有月的总计
        $res_uid = Db::name('shop_order_goods')->alias('og')
            ->join('shop_order o', 'og.order_id = o.id')
            ->join('shop_goods g', 'og.goods_id = g.id')
            ->field('sum(og.pay_price * og.number) as total_amount,og.goods_id,og.goods_name,group_concat(og.id) as order_goods_id')
            ->where($where)
            ->group('og.goods_id')
            ->order('total_amount desc')
            ->limit(($param['page'] - 1) * $param['limit'], $param['limit'])->select()->toArray();

        // 获取当前页商品订单数据
        $order_goods_id = explode(',', implode(',',array_column($res_uid,'order_goods_id')));
        $arr = array_column($res_uid,null,'goods_id');

        $owhere = [];
        $owhere = [
            ['og.id', 'in', $order_goods_id]
        ];
        $all_order_goods = Db::name('shop_order_goods')->alias('og')
            ->join('shop_order o', 'og.order_id = o.id')
            ->field('og.pay_price * og.number as pay_amount,og.goods_id,month(from_unixtime(o.create_time)) as month')
            ->where($owhere)
            ->select()->toArray();

        foreach($all_order_goods as $key => $value)
        {
            $list[$value['goods_id']][] = $value;
        }

        foreach($list as $key => $value)
        {
            foreach($value as $kv => $va)
            {
                if(isset($valueArr[$va['month']]))
                {
                    $valueArr[$va['month']] = $valueArr[$va['month']] +  $va['pay_amount'];
                }
                else{
                    $valueArr[$va['month']] = $va['pay_amount'];
                }
            }
            foreach($month as $k => $v)
            {
                if(isset($valueArr[$v]))
                {
                    $arr[$key]['month_' . $v] = $valueArr[$v] . '';
                }
                else{
                    $arr[$key]['month_' . $v] = '--';
                }
            }
            unset($valueArr);
        }
        
        // 总计
        $totalArr = [
            'goods_id' => 0,
            'goods_name' => '总计',
            'total_amount' => $total_amount .'',
            'order_goods_id' => ''
        ];
        $totalArr = $totalArr + $month_pay_amount;

        $data = [];
        $data['dataCount'] = $dataCount ?? 0;

        array_unshift($arr, $totalArr);

        $data['list'] = $arr ?? [];
        return $data;
    }

    /**
     * 数据大屏
     * @param  array $request 请求参数
     * @return array[]
     * @author Mr.Liu Wuchen
     * @create 2021-09-07 10:07
     */
    public function getMapData(array $request): array
    {
        // 1、客户转换情况
        $data = $this->getMonthNewData();
        $ret  = [
            ['value' => $data['leads_num'], 'name' => '线索', 'itemStyle' => ['color' => '#F7931E']],
            ['value' => $data['customer_num'], 'name' => '客户', 'itemStyle' => ['color' => '#00FFFF']],
            ['value' => $data['business_num'], 'name' => '商机', 'itemStyle' => ['color' => '#FCEE21']],
            ['value' => $data['deal_customer_num'], 'name' => '成交客户', 'itemStyle' => ['color' => '#0068FF']],
        ];
        $return['map_1'] = $ret;

        // 2、各区商机处理统计
        $data = $this->getAreaBusinessTop($request);
        $list = $data['data'] ?? [];
        $businessNum = array_column($list, 'business_num');
        $auditNum    = array_column($list, 'audit_num');
        $province    = array_column($list, 'province_name');
        $businessNum = count($businessNum) < 5 ? array_pad($businessNum, 5, 0) : $businessNum;
        $auditNum    = count($auditNum) < 5 ? array_pad($auditNum, 5, 0) : $auditNum;
        $province    = count($province) < 5 ? array_pad($province, 5, '暂无数据') : $province;
        $ret  = [
            'data_1' => $businessNum,
            'data_2' => $auditNum,
            'data_3' => $province
        ];
        $return['map_2'] = $ret;

        // 3、待处理事项
        $ret  = [];
        $data = $this->getWaitHandle($request);
        $list = $data['data'] ?? [];
        $titleArr = ['待进入公海的线索', '公海', '处理中的商机', '超时未跟进的商机', '未回款的订单', '审批中的试样申请'];
        $colorArr = ['#F7931E', '#00FFFF', '#FCEE21', '#0068FF', '#E05C6A', '#D3CE26'];
        $keyNum   = 0;
        foreach ($list as $key => $value) {
            $ret[] = ['value' => $value, 'name' => $titleArr[$keyNum], 'itemStyle' => ['color' => $colorArr[$keyNum]]];
            $keyNum++;
        }
        $return['map_3'] = $ret;

        // 4、地图
        $regionLngLat = $this->getRegionLngLat();
        $data = $this->getAreaCustomer($request);
        $ret  = [];
        foreach ($data as $key => $value) {
            $lng = $regionLngLat[$value['province_name']]['lng'] ?? '';
            $lat = $regionLngLat[$value['province_name']]['lat'] ?? '';
            if (!$lng || !$lat) {
                continue;
            }
            $val = [
                $lng,
                $lat,
                300,
                $value['leads_num'],
                $value['communal_num'],
                $value['customer_num'],
                $value['customer_deal_num'],
                $value['order_amount']
            ];
            $ret[] = ['name' => $value['province_name'], 'value' => $val];
        }
        $return['map_4'] = $ret;

        // 5、月度订单统计
        $data = $this->getDataList(['year' => date('Y')]);
        $ret  = [
            'data_1' => array_column($data, 'pay_amount'),
            'data_2' => array_column($data, 'customer_num')
        ];
        $return['map_5'] = $ret;

        // 6、月客户订单总金额
        $data   = $this->getCustomerTopDataList($request);
        $amount = array_column($data, 'total_amount');
        $name   = array_column($data, 'customer_name');
        $amount = count($amount) < 5 ? array_pad($amount, 5, 0) : $amount;
        $name   = count($name) < 5 ? array_pad($name, 5, '暂无客户') : $name;
        $ret    = [
            'data_1' => $amount,
            'data_2' => $name,
        ];
        $return['map_6'] = $ret;

        // 7、月标品销售金额排行
        $data     = $this->getGoodsTopDataList($request);
        $colorArr = ['#DF5A6B', '#FFDA52', '#37D7F2', '#2F64E6', '#CFCD28'];
        $ret      = [];
        foreach ($data as $key => $value) {
            $ret[] = ['value' => $value['total_amount'], 'name' => $value['goods_name'], 'itemStyle' => ['color' => $colorArr[$key]]];
        }
        $return['map_7'] = $ret;

        // 8、月试样申请统计
        $data = $this->getSampleApplyTop($request);
        $list = $data['data'] ?? [];
        $ret  = [
            // ['申请次数', '申请数量', '商品名称']
            ['申请数量', '商品名称']
        ];
        foreach ($list as $key => $value) {
            // $ret[] = [$value['apply_num'], $value['apply_quantity_value'], $value['goods_name']];
            $ret[] = [$value['apply_quantity_value'], $value['goods_name']];
        }
        $ret = count($ret) < 6 ? array_pad($ret, 6, ['0', '商品名称']) : $ret;
        $return['map_8'] = $ret;

        return ['data' => $return];
    }

    /**
     * 获取省份坐标
     *
     * @return array
     */
    public function getRegionLngLat(): array
    {
        return [
            '北京' => [
              'name' => '北京',
              'lng' => 116.404999,
              'lat' => 39.904999,
            ],
            '天津' => [
              'name' => '天津',
              'lng' => 117.190002,
              'lat' => 39.125599,
            ],
            '河北省' => [
              'name' => '河北省',
              'lng' => 114.501999,
              'lat' => 38.045502,
            ],
            '山西省' => [
              'name' => '山西省',
              'lng' => 112.549004,
              'lat' => 37.856998,
            ],
            '内蒙古自治区' => [
              'name' => '内蒙古自治区',
              'lng' => 111.670998,
              'lat' => 40.818298,
            ],
            '辽宁省' => [
              'name' => '辽宁省',
              'lng' => 123.429001,
              'lat' => 41.796799,
            ],
            '吉林省' => [
              'name' => '吉林省',
              'lng' => 125.324997,
              'lat' => 43.886799,
            ],
            '黑龙江省' => [
              'name' => '黑龙江省',
              'lng' => 126.641998,
              'lat' => 45.757,
            ],
            '上海' => [
              'name' => '上海',
              'lng' => 121.473,
              'lat' => 31.231701,
            ],
            '江苏省' => [
              'name' => '江苏省',
              'lng' => 118.766998,
              'lat' => 32.0415,
            ],
            '浙江省' => [
              'name' => '浙江省',
              'lng' => 120.153999,
              'lat' => 30.2875,
            ],
            '安徽省' => [
              'name' => '安徽省',
              'lng' => 117.282997,
              'lat' => 31.8612,
            ],
            '福建省' => [
              'name' => '福建省',
              'lng' => 119.306,
              'lat' => 26.0753,
            ],
            '江西省' => [
              'name' => '江西省',
              'lng' => 115.891998,
              'lat' => 28.6765,
            ],
            '山东省' => [
              'name' => '山东省',
              'lng' => 117.000999,
              'lat' => 36.6758,
            ],
            '河南省' => [
              'name' => '河南省',
              'lng' => 113.665001,
              'lat' => 34.757999,
            ],
            '湖北省' => [
              'name' => '湖北省',
              'lng' => 114.299004,
              'lat' => 30.5844,
            ],
            '湖南省' => [
              'name' => '湖南省',
              'lng' => 112.982002,
              'lat' => 28.194099,
            ],
            '广东省' => [
              'name' => '广东省',
              'lng' => 113.280998,
              'lat' => 23.1252,
            ],
            '广西壮族自治区' => [
              'name' => '广西壮族自治区',
              'lng' => 108.32,
              'lat' => 22.823999,
            ],
            '海南省' => [
              'name' => '海南省',
              'lng' => 110.331001,
              'lat' => 20.032,
            ],
            '重庆' => [
              'name' => '重庆',
              'lng' => 106.504997,
              'lat' => 29.533199,
            ],
            '四川省' => [
              'name' => '四川省',
              'lng' => 104.066002,
              'lat' => 30.6595,
            ],
            '贵州省' => [
              'name' => '贵州省',
              'lng' => 106.712997,
              'lat' => 26.5783,
            ],
            '云南省' => [
              'name' => '云南省',
              'lng' => 102.711998,
              'lat' => 25.0406,
            ],
            '西藏自治区' => [
              'name' => '西藏自治区',
              'lng' => 91.132202,
              'lat' => 29.6604,
            ],
            '陕西省' => [
              'name' => '陕西省',
              'lng' => 108.947998,
              'lat' => 34.263199,
            ],
            '甘肃省' => [
              'name' => '甘肃省',
              'lng' => 103.823997,
              'lat' => 36.057999,
            ],
            '青海省' => [
              'name' => '青海省',
              'lng' => 101.778999,
              'lat' => 36.623199,
            ],
            '宁夏回族自治区' => [
              'name' => '宁夏回族自治区',
              'lng' => 106.278,
              'lat' => 38.4664,
            ],
            '新疆维吾尔自治区' => [
              'name' => '新疆维吾尔自治区',
              'lng' => 87.617699,
              'lat' => 43.792801,
            ],
            '台湾省' => [
              'name' => '台湾省',
              'lng' => 121.509003,
              'lat' => 25.0443,
            ],
            '香港特别行政区' => [
              'name' => '香港特别行政区',
              'lng' => 114.172997,
              'lat' => 22.32,
            ],
            '澳门特别行政区' => [
              'name' => '澳门特别行政区',
              'lng' => 113.549004,
              'lat' => 22.198999,
            ]
        ];
    }

}